package com.slt.concurrency.mashibing2019.juc.c_007_LockAndTools.exercise;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLock01 {
    static ReentrantLock reentrantLock = new ReentrantLock();
    //ReadWriteLock 不是lock的子接口
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();


    static void read(Lock lock){
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            System.out.println("read over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    static void write(Lock lock){
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            System.out.println("write over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
//        for (int i = 0; i < 10; i++) {
//            new Thread(()->read(readLock)).start();
//        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->write(writeLock)).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->read(reentrantLock)).start();
        }
    }
}
